package com.liu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liu.entity.Student;
import com.liu.service.StudentService;
import com.liu.vo.DataView;
import com.liu.vo.StudentVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class StudentContrller {

    @Autowired
    private StudentService studentService;

    @RequestMapping("toStudent")
    public String toStudent(){
        return "admin/student";
    }

    /**
     * 模糊查询和根据姓名，学号查询所有学生
     * @param studentVo
     * @return
     */
    @RequestMapping("/listStudent")
    @ResponseBody
    public DataView listStudent(StudentVo studentVo){
        //查询带有模糊查询 带有分页
        IPage<Student> page = new Page<>(studentVo.getPage(),studentVo.getLimit());
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();

        queryWrapper.like(studentVo.getId() != null, "id", studentVo.getId());
        queryWrapper.like(studentVo.getName() != null,"name", studentVo.getName());

        studentService.page(page,queryWrapper);
        DataView dataView = new DataView(page.getTotal(), page.getRecords());

        return dataView;
    }


    /**
     * 添加学生
     * @param student
     * @return
     */
    @RequestMapping("/addStudent")
    @ResponseBody
    public DataView addStudent(Student student){
        boolean b = studentService.saveOrUpdate(student);
        DataView dataView = new DataView();

        if(b){
            dataView.setCode(200);
            dataView.setMsg("添加学生成功");
            return dataView;
        }
        dataView.setCode(100);
        dataView.setMsg("添加学生失败");
        return dataView;
    }

    /**
     * 删除学生
     */
    @RequestMapping("/deleteStudent")
    @ResponseBody
    public DataView deleteStdudent(Integer id){
        DataView dataView = new DataView();
        studentService.removeById(id);
        dataView.setCode(200);
        dataView.setMsg("删除学生成功");
        return dataView;
    }
}
